package com.sgb.kjwl.view.ui.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.im.immodel.IMUtils;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.jicai.view.activity.FactoryCentralizedActivity;
import com.sgb.jicai.view.activity.JcMyPriceActivity;
import com.sgb.jicai.view.activity.JiCaiDaTingActivity;
import com.sgb.jicai.view.activity.JiCaiDemanderPublishAct;
import com.sgb.jicai.view.activity.JiCaiSupplierPublishAct;
import com.sgb.jicai.view.activity.MyCenterMyJoinActivity;
import com.sgb.jicai.view.activity.XuFangFaQiActivity;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.BuildConfig;
import com.sgb.kjwl.R;
import com.sgb.kjwl.aspectj.login.ILogin;
import com.sgb.kjwl.aspectj.login.LoginCheck;
import com.sgb.kjwl.aspectj.login.LoginSDK;
import com.sgb.kjwl.databinding.ActivityMainBinding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.UserAuthMsgEntity;
import com.sgb.kjwl.pop.MainPublishDialog;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.MapUtils;
import com.sgb.kjwl.utils.UpdateUtils;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.kjwl.view.event.CategoryEvent;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.sgb.kjwl.view.event.InstallEvent;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.WebEvent2;
import com.sgb.kjwl.view.event.special.QuickEntryEvent;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.ShoppingCartActivity;
import com.sgb.kjwl.view.ui.activity.chat.ContactBookActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.AddNeedListActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.MakeOverActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.MakeOverPublishMainActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.NeedActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.ProfessionalQuoteActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.ProfessionalTeamChangeActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.PublishServiceListActivity;
import com.sgb.kjwl.view.ui.activity.house.LeaseHousesActivity;
import com.sgb.kjwl.view.ui.activity.lease.LeaseHallActivity2;
import com.sgb.kjwl.view.ui.activity.leaseAsk.MyAskLeaseActivity;
import com.sgb.kjwl.view.ui.activity.leaseAsk.publish.AskLeaseFactoryActivity2;
import com.sgb.kjwl.view.ui.activity.leaseAsk.publish.AskLeaseFarmActivity2;
import com.sgb.kjwl.view.ui.activity.leaseAsk.publish.AskLeaseHouseActivity2;
import com.sgb.kjwl.view.ui.activity.leaseAsk.publish.AskLeaseLandActivity2;
import com.sgb.kjwl.view.ui.activity.leaseAsk.publish.PublishLeaseInfoActivity2;
import com.sgb.kjwl.view.ui.activity.manage.CompanyTradesActivity;
import com.sgb.kjwl.view.ui.activity.manage.EpAssestActivity;
import com.sgb.kjwl.view.ui.activity.manage.IPActivity;
import com.sgb.kjwl.view.ui.activity.manage.ManageActivity;
import com.sgb.kjwl.view.ui.activity.manage.SpecialQualificationActivity;
import com.sgb.kjwl.view.ui.activity.manage.TradeHonorActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebSiteInquiryActivity;
import com.sgb.kjwl.view.ui.activity.material.GoodsAggregateActivity;
import com.sgb.kjwl.view.ui.activity.packers.PackersEmploymentActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickBiddingListActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickListActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickNoticeActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickWinningNoticeActivity;
import com.sgb.kjwl.view.ui.activity.self.ApprovalManagerActvity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.TeamAuthListActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.PublishCargoActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.LaborServiceAndEmploymentPublishActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamEmploymentEditActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamIntroduceActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamOfferEditActivity;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfWorkerPublishActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.CarPublishActivity1;
import com.sgb.kjwl.view.ui.activity.self.publish.DevicePublishActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.GoodsPublishActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.LeaseFactoryActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.LeaseFarmActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.LeaseLandActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.LeaseMachineActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.ChangePasswordActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.BiddingTransportHallActivity;
import com.sgb.kjwl.view.ui.activity.transport.DriverLookForGoodsActivity;
import com.sgb.kjwl.view.ui.activity.transport.GoodsCarsActivity;
import com.sgb.kjwl.view.ui.adapter.home.BottomMeumAdapter;
import com.sgb.kjwl.view.ui.fragment.CategoryFragment4;
import com.sgb.kjwl.view.ui.fragment.CategoryLeaseFragment;
import com.sgb.kjwl.view.ui.fragment.CategoryMemberFragment;
import com.sgb.kjwl.view.ui.fragment.ChatFragment;
import com.sgb.kjwl.view.ui.fragment.HomeFragment3;
import com.sgb.kjwl.view.ui.fragment.SelfFragment5;
import com.sgb.kjwl.view.ui.fragment.enterprise.ServiceClassFragment;
import com.sgb.kjwl.view.ui.fragment.freightTransport.MapGoodsAndCarFragment;
import com.sgb.kjwl.view.ui.fragment.packers.FigureCheckFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickCategoryFragment;
import com.sgb.kjwl.view.ui.quickentry.BackResultContentListener;
import com.sgb.kjwl.view.ui.quickentry.QuickEntryClickListener;
import com.sgb.kjwl.view.ui.quickentry.QuickEntryEntity;
import com.sgb.kjwl.view.ui.quickentry.QuickEntryPopWindow;
import com.sgb.kjwl.view.widget.SeekingRentSecondPublishDialog;
import com.sgb.kjwl.view.widget.drop.DropCover;
import com.sgb.kjwl.view.widget.drop.DropManager;
import com.sgb.kjwl.view.widget.jicai.HomeJiCaiPublishMenuPop;
import com.sgb.kjwl.view.widget.transport.LogisticsWorkbench;
import com.sgb.kjwl.viewmodel.home.MainModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.router.PathLogin;
import com.sgb.link.router.PathLogistics;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.router.PathTeam;
import com.sgb.member.MemberConfig;
import com.sgb.member.ui.activity.MemberAuditActivity;
import com.sgb.member.ui.activity.MemberInviteOrApplyActivity;
import com.sgb.member.ui.activity.MemberManageActivity;
import com.sgb.zhaocai.utils.PickUtil;
import com.sgb.zhaocai.view.demand.activity.DemandForecastActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.LoginTokenEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.ButtonClickUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.view.entity.MenuEntity;
import com.ycbjie.webviewlib.utils.X5WebUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import pl.droidsonroids.gif.GifDrawable;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;
import retrofit2.Response;

import static com.swgk.core.event.EventConstant.EVENT_INSTALL_APP;
import static com.swgk.core.util.ACAdminDialogUtils.MK_ADDCOMMODITY;
import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;

public class MainActivity extends AppActivity implements QuickEntryClickListener {
    private static final String EXTRA_APP_QUIT = "APP_QUIT";
    //未登录
    public final int CODE_NO_LOGING = 0;
    //登录并且为个人身份
    public final int CODE_LOGING_MY = 1;
    //登录并且为企业身份
    public final int CODE_LOGING_QY = 2;
    //登录并且为组织身份
    public final int CODE_LOGING_ZZ = 3;
    //登录并且为团队身份
    public final int CODE_LOGING_TD = 4;
    @Inject
    MainModel viewModel;
    public static final int FRAGMENT_HOME = 0; //首页
    public static final int FRAGMENT_CHAT = 1;
    public static final int FRAGMENT_BUSINESS = 5;
    public static final int FRAGMENT_SHOPPING = 2;
    public static final int FRAGMENT_SELF = 3;
    public static final int FRAGMENT_MAIN_RECRUITMENT = 4;
    public static final int PUBLISH = 5;
    public static final int FRAGMENT_CATEGORY = 6;//分类
    private ActivityMainBinding binding;
    private FragmentManager fragmentManager;
    private final Fragment[] myFragment = new Fragment[7];
    private long exitTime;
    private int currentIndex = 0; //当前Fragment的显示位置
    private int chooseIndex = 0;
    private static String showPage;
    private long lastClickTime;
    private static int mCheckId;
    private boolean isPick;
    private boolean isUpdateUnread = true; //是否在此更新未读消息
    private List<MenuEntity> menulist = new ArrayList<>();
    //private String selectTab = "";
    private int selectId = -1;
    private String isEnterpriseAuth = "";
    private String isDriverAuth = "";
    private String mpublishSelectedName;
    private boolean isPersonAuth = false;
    //是否关联企业 0：未关联；1：关联
    private String RELEVANCE = "";
    //是否有企业操作权限 false：没有；true：有
    private boolean IS_GOODS_PUBLISH = false;
    public static final int REQUEST_CODE = 10012;

    private QBadgeView qBadgeView;

    public int state;
    //发布弹窗
    private MainPublishDialog mainPublishDialog;

    private int number = 3; // 读秒
    private boolean isInit = false;//首页是否初始化完成
    int tabTypeId;
    String mineTabTypeName = "";
    //String tabTypeName = "";//当前homeFragment的选中
    AlertDialog mDialog;
    private BottomSheetBehavior<RelativeLayout> bottomSheetBehavior;
    private ObjectAnimator startalpha;
    private ObjectAnimator finishalpha;
    private BottomMeumAdapter bottomMeumAdapter;
    LogisticsWorkbench logisticsWorkbench;

    private ActivityResultLauncher<Intent> launchForesult;
    private String JiCaitype;

    private QuickEntryPopWindow quickEntryPopWindow; //快捷入口选首弹框

    //是否显示广告
    private static boolean isShowAd = true;

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras, int type) {
        if (extras == null) {
            Intent intent = new Intent();
            intent.setClass(context, MainActivity.class);
            intent.putExtra("type", type);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(intent);
        }
    }

    public static void start(Context context, Intent extras) {
        if (extras == null) {
            Intent intent = new Intent();
            intent.setClass(context, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(intent);
        } else {
            extras.setClass(context, MainActivity.class);
            extras.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(extras);
            showPage = extras.getStringExtra("showPage");
        }
    }


    public static void start(PreferredChoiceActivity preferredChoiceActivity, Intent extras) {
        extras.setClass(preferredChoiceActivity, MainActivity.class);
        mCheckId = extras.getIntExtra("checkId", -1);
        isShowAd = extras.getBooleanExtra("isShowAd", true);
        preferredChoiceActivity.startActivity(extras);
    }

    @Override
    protected boolean statusBarDark() {
        return false;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //不保留后台活动，从厂商推送进聊天页面，会无法退出聊天页面
        if (msavedInstanceState == null && parseIntent()) {
            return;
        }
    }

    @Override
    public void checkingPermission() {
        if (PermissionsUtil.hasPermission(getActivity(), BASIC_EXTERNAL_STORAGE)) {
            X5WebUtils.init(getApplication());
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    X5WebUtils.init(getApplication());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                }
            }, BASIC_EXTERNAL_STORAGE);
        }
    }

    private boolean parseIntent() {
        Intent intent = getIntent();
        if (intent.hasExtra(EXTRA_APP_QUIT)) {
            intent.removeExtra(EXTRA_APP_QUIT);
            jumpLogin();
            return true;
        }
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);
    }

    @SuppressLint({"AutoDispose", "CheckResult"})
    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);

        if (isShowAd) {
            //广告功能
            showAdTime();
        } else {
            showMainActivity(null);
        }
        //初始化底部菜单“我的”头像及名称显示
        initMeMenu();
        //初始化底部导航
        initBottomNavigation();
        //底部动态菜单
        bottomDynamicMenu();

        Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    initFragment(msavedInstanceState);
                    showTabView(FRAGMENT_HOME);
                });
        viewModel.getPermissionHuiYuan();
    }

    public void initMeMenu() {
        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
            upDataMyTabIcom("未登录", "");
        } else {
            int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (type == 0) {
                String title = "";
                boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                //判断实名认证
                if (personAuth) {
                    title = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
                    String img = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMP_LOGO, "");
                    if (!TextUtils.isEmpty(title) && title.length() > 4) {
                        title = title.substring(0, 4);
                    }
                    upDataMyTabIcom(title, img);
                } else {
                    title = "未实名";
                    upDataMyTabIcom(title, R.mipmap.app_tab_self_name_off);
                }
            }
            if (type == 1) {
                String title = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
                String img = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMP_LOGO, "");
                if (!TextUtils.isEmpty(title) && title.length() > 4) {
                    title = title.substring(0, 4);
                }
                if (TextUtils.isEmpty(img)) {
                    upDataMyTabIcom(title, R.mipmap.icon_default_company_self);
                } else {
                    upDataMyTabIcom(title, img);
                }
            }
            if (type == 2) {
                String title = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
                String img = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMP_LOGO, "");
                if (!TextUtils.isEmpty(title) && title.length() > 4) {
                    title = title.substring(0, 4);
                }
                if (TextUtils.isEmpty(img)) {
                    upDataMyTabIcom(title, R.mipmap.icon_team_default_1);
                } else {
                    upDataMyTabIcom(title, img);
                }
            }
            if (type == 3) {
                String title = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
                String img = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMP_LOGO, "");
                if (!TextUtils.isEmpty(title) && title.length() > 4) {
                    title = title.substring(0, 4);
                }
                if (TextUtils.isEmpty(img)) {
                    upDataMyTabIcom(title, R.drawable.icon_organization_default);
                } else {
                    upDataMyTabIcom(title, img);
                }
            }
        }
    }


    //底部动态菜单
    private void bottomDynamicMenu() {
        binding.bottomNavigationLayout.bottomRv.setLayoutManager(new GridLayoutManager(MainActivity.this, 5));
        bottomMeumAdapter = new BottomMeumAdapter(MainActivity.this, null);
        bottomMeumAdapter.setOnItemClick(new AdapterOnItemClick<MenuEntity>() {
            @Override
            public void onItemClick(MenuEntity menuEntity, int position) {
                switch (menuEntity.getName()) {
                    case "待办":
                        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                            EventBus.getDefault().postSticky("transport_to_login");
                        } else {
                            ApprovalManagerActvity.start(MainActivity.this, 0);
                        }
                        break;
                    case "通讯录":
                        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            jumpLogin();
                        } else {
                            ContactBookActivity.start(getActivity());
                        }
                        break;
                    case "采购单":
                        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                            EventBus.getDefault().postSticky("transport_to_login");
                        } else {
                            ShoppingCartActivity.start(getActivity());
                        }
                        break;
                    case "申请":
                        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                            EventBus.getDefault().postSticky("transport_to_login");
                        } else {
                            String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                            boolean isPerson = TextUtils.isEmpty(companyNo) || "0".equals(companyNo);
                            if (isPerson) {
                                boolean isAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                                if (isAuth) {
                                    MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                                } else {
                                    ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_NEW_AC, getActivity());
                                }
                            } else {
                                MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 1);
                            }
                        }
                        break;
                    case "邀请":
                        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                            EventBus.getDefault().postSticky("transport_to_login");
                        } else {
                            String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                            boolean isPerson = TextUtils.isEmpty(companyNo) || "0".equals(companyNo);
                            if (isPerson) {
                                boolean isAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                                if (isAuth) {
                                    MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                                } else {
                                    ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_NEW_AC, getActivity());
                                }
                            } else {
                                MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                            }

                        }
                        break;
                    case "商机":
                        MToast.showLongToast1(MainActivity.this, "功能开发中，敬请期待", Gravity.CENTER);
                        break;
                    case "会员":
                        EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 24));
                        break;
                    case "报价":
                        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                            EventBus.getDefault().postSticky("transport_to_login");
                        } else {
                            int TYPE = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                            if (TYPE != 1) {
                                ACAdminDialogUtils.showACDialogForPublish(ACAdminDialogUtils.TYPE_NO_AC, getActivity(), new ACAdminDialogUtils.DialogClick() {

                                    @Override
                                    public void dialogClick3() {
                                        displayFrg(FRAGMENT_SELF);
                                    }
                                });
                            } else {
                                viewModel.isHasQuotationAuth();
                            }
                        }
                        break;
                    case "订单":
                        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
                            EventBus.getDefault().postSticky("transport_to_login");
                        } else {
                            int TYPE = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                            if (TYPE == 0) {
                                boolean isAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                                if (isAuth) {
                                    viewModel.isHasOrderAuth();
                                } else {
                                    ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_NEW_AC, getActivity());
                                }
                            }
                            if (TYPE == 1) {
                                viewModel.isHasOrderAuth();
                            }
                            if (TYPE == 2) {
                                MToast.showToast(getActivity(), "当前身份无权限");
                            }
                        }
                        break;
                    case "设置首页":
                        if (ClickUtils.isFastClick()) {
                            PreferredChoiceActivity.start(getActivity(), false);
                            finish();
                        }
                        break;
                    case "企管帮":
                        openQgb();
                        break;
                }
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
        binding.bottomNavigationLayout.bottomRv.setAdapter(bottomMeumAdapter);
        binding.contentLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
                return true;
            }
        });
        qBadgeView = new QBadgeView(this);
        //在view上显示小圆
        qBadgeView.bindTarget(binding.bottomNavigationLayout.tabChat);
        //设置是否为精确模式数
        qBadgeView.setExactMode(false);
        //设置外边距
        qBadgeView.setGravityOffset(15, 0, true);
        //设置背景颜色
        qBadgeView.setBadgeBackgroundColor(ContextCompat.getColor(this, R.color.color_EF4033));
        //显示阴影 false隐藏阴影
        qBadgeView.setShowShadow(false);
        //打开拖拽消除模式并设置监听
        qBadgeView.setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
            @Override
            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                updateTabBarUnreadMsg(0);
            }
        });
    }

    //尝试打开企管帮
    private void openQgb() {
        //企管帮包名
        String APP_PACKAGE_NAME = "com.sgb.management";
        //判读是否有相关包名注册来判断该APP是否安装
        if (MapUtils.isAppInstalled(this, APP_PACKAGE_NAME)) {
            Intent intent = new Intent();
            Uri uri = Uri.parse("web2app://qgbapp/welcome?showPage=FRAGMENT_BUSINESS");
            intent.setData(uri);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                //已安装的企管帮版本过低，还未添加上边的scheme处理代码
                MToast.showToast(this, "您安装的企管帮版本过低，无法唤起，请及时更新");
            }
        } else {
            openMarket(APP_PACKAGE_NAME);
        }
    }

    //打开应用市场
    private void openMarket(String packageName) {
        Uri uri = Uri.parse("market://details?id=" + packageName);
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(goToMarket);
        } catch (Exception e) {
        }
    }

    /**
     * 返回是否有经营商品-我的报价权限
     *
     * @param b
     */
    public void resultHasQuotationAuth(boolean b) {
        if (b) {
            ARouter.getInstance().build(Constants.ARouter.AR_SHOP_MY_PRICE).navigation();
        } else {
            ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_NO_OPERATE_PERMISSION, getActivity());
        }
    }

    /**
     * 初始化底部导航
     */
    private void initBottomNavigation() {
        binding.bottomNavigationLayout.tabHome.setOnClickListener(this);
        binding.bottomNavigationLayout.tabChat.setOnClickListener(this);
//        binding.tabShopping.setOnClickListener(this);
        binding.bottomNavigationLayout.tabSelf.setOnClickListener(this);
        binding.bottomNavigationLayout.tabBusiness.setOnClickListener(this);
        binding.bottomNavigationLayout.tabPublish.setOnClickListener(this);
        binding.bottomNavigationLayout.tabFenlei.setOnClickListener(this);
        bottomSheetBehavior = BottomSheetBehavior.from(binding.bottomNavigationLayout.contextLayout);
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_COLLAPSED:
                        //折叠状态
                        LogUtil.i("BottomSheetBehavior", "折叠状态");
//                        endBottomNavigationAnim();
//                        binding.contentLayout.setVisibility(View.GONE);
//                        binding.bottomNavigationLayout.hideArrow.setVisibility(View.GONE);
                        binding.bottomNavigationLayout.showArrow.setVisibility(View.VISIBLE);
                        categoryDisplay();
                        binding.bottomNavigationLayout.contextLayout.setBackgroundResource(R.color.transparent);
                        binding.bottomNavigationLayout.tabLayout.setBackgroundResource(R.color.color_FFFFFF);
                        setFinishAnimate();
//                        AlphaUtils.clearAlpha(this@MainActivity)
                        break;
                    case BottomSheetBehavior.STATE_DRAGGING:
                        categoryDisplay();
                        //过渡状态，此时用户正在拖动
//                        LogUtils.i("BottomSheetBehavior", "拖动状态");
                        binding.bottomNavigationLayout.showArrow.setVisibility(View.GONE);
//                        binding.contentLayout.setVisibility(View.VISIBLE);
                        binding.bottomNavigationLayout.contextLayout.setBackgroundResource(R.drawable.bg_home_bottom_arrow);
                        binding.bottomNavigationLayout.tabLayout.setBackgroundResource(R.color.transparent);
                        break;
                    case BottomSheetBehavior.STATE_EXPANDED:
                        categoryDisplay();
                        //完全展开
//                        LogUtils.i("BottomSheetBehavior", "完全展开");
//                        AlphaUtils.setAlpha(this@MainActivity)
//                        binding.bottomNavigationLayout.hideArrow.setVisibility(View.VISIBLE);
                        binding.bottomNavigationLayout.contextLayout.setBackgroundResource(R.drawable.bg_home_bottom_arrow);
                        binding.bottomNavigationLayout.tabLayout.setBackgroundResource(R.color.transparent);
                        binding.bottomNavigationLayout.showArrow.setVisibility(View.GONE);
//                        startBottomNavigationAnim();
                        setStartAnimate();
                    case BottomSheetBehavior.STATE_HIDDEN:
                        //隐藏状态
                        LogUtil.i("BottomSheetBehavior", "隐藏状态");
//                        AlphaUtils.clearAlpha(this@MainActivity)
                    case BottomSheetBehavior.STATE_SETTLING:
                        //脱离手指自由滑动状态
                        LogUtil.i("BottomSheetBehavior", "脱离手指自由滑动状态");
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + newState);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            }
        });
    }

    //处理个人与企业在不同情况下的菜单显示
    public void categoryDisplay() {
        String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (tabTypeId == 21 || tabTypeId == 1) {
            //个人中心
            if (no.equals("0")) {
                //当在个人中心点击推荐或者商品时，隐藏待办
                viewModel.categoryDisplayData(1, true, bottomMeumAdapter);
            } else {
                //当在公司点击推荐或者商品时，隐藏待办
                viewModel.categoryDisplayData(1, false, bottomMeumAdapter);
            }
        } else {
            //当在个人中心点击其他时，隐藏待办
            if (no.equals("0")) {
                viewModel.categoryDisplayData(2, true, bottomMeumAdapter);
                //当在个人中心点击其他时，显示待办
            } else {
                viewModel.categoryDisplayData(2, false, bottomMeumAdapter);
            }
        }
    }

    /**
     * 属性动画
     * 渐变(开始)
     */
    private void setStartAnimate() {
        //      创建属性动画对象，并设置移动的方向和偏移量
        //      rotation是imageView的旋转属性
        if (startalpha == null) {
            startalpha = ObjectAnimator.ofFloat(binding.contentLayout, "alpha", 0f, 1f);
            startalpha.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    binding.contentLayout.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
        ObjectAnimator objectAnimator = startalpha;
        //      设置移动时间
        objectAnimator.setDuration(300);
        //      开始动画
        objectAnimator.start();
    }

    /**
     * 属性动画
     * 渐变(结束)
     */
    private void setFinishAnimate() {
        //      创建属性动画对象，并设置移动的方向和偏移量
        //      rotation是imageView的旋转属性
        if (finishalpha == null) {
            finishalpha = ObjectAnimator.ofFloat(binding.contentLayout, "alpha", 1f, 0f);
            finishalpha.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    binding.contentLayout.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
        ObjectAnimator objectAnimator = finishalpha;
        //      设置移动时间
        objectAnimator.setDuration(300);
        //      开始动画
        objectAnimator.start();
    }

    @Override
    protected void init() {
        initUnreadCover();
    }

    @Override
    protected void onStart() {
        super.onStart();
        upDateApk();
        if ("FRAGMENT_SHOPPING".equals(showPage)) {
            showShoppingCarView();
            showPage = "";
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //跳转到个人中心
        if ("FRAGMENT_ME".equals(intent.getStringExtra("showPage"))) {
            showTabView(FRAGMENT_SELF);
            displayFrg(FRAGMENT_SELF);
        }

        //跳转到消息
        if ("FRAGMENT_CHAT".equals(intent.getStringExtra("showPage"))) {
            showTabView(FRAGMENT_CHAT);
            displayFrg(FRAGMENT_CHAT);
        }

        //跳转到首页
        if ("FRAGMENT_MAIN".equals(intent.getStringExtra("showPage"))) {
            showTabView(FRAGMENT_HOME);
            displayFrg(FRAGMENT_HOME);
        }

        //跳转到图查
        if ("FRAGMENT_TUCHA".equals(intent.getStringExtra("showPage"))) {
            String position = intent.getStringExtra("position");
            if (!TextUtils.isEmpty(position)) {
                if (position.equals("2")) {
                    EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_PAGE_SKIP_TUCHA, 2));
                } else if (position.equals("0")) {
                    EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_PAGE_SKIP_TUCHA, 0));
                }
            }
            showTabView(FRAGMENT_CATEGORY);
            displayFrg(FRAGMENT_CATEGORY);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 主界面布局加载
     *
     * @param savedInstanceState
     */
    private void initFragment(Bundle savedInstanceState) {
        fragmentManager = getSupportFragmentManager();
        //检查并移除缓存页面
        if (savedInstanceState != null && !fragmentManager.getFragments().isEmpty()) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            for (Fragment fragment : fragmentManager.getFragments()) {
                transaction.remove(fragment);
            }
            transaction.commitAllowingStateLoss();
        }
        if (savedInstanceState == null || !isInit) {
            myFragment[FRAGMENT_HOME] = new HomeFragment3();

            Bundle bundle = new Bundle();
            if (mCheckId != -1) {
                bundle.putInt("checkId", mCheckId);
            } else {
                bundle.putInt("checkId", -1);
            }
            myFragment[FRAGMENT_HOME].setArguments(bundle);//数据传递到fragment中

            if (tabTypeId == 6) {
                myFragment[FRAGMENT_CATEGORY] = MapGoodsAndCarFragment.getInstance(false);
            } else if (tabTypeId == 4) {
                myFragment[FRAGMENT_CATEGORY] = CategoryLeaseFragment.newInstance();
            } else if (tabTypeId == 24) {
                myFragment[FRAGMENT_CATEGORY] = CategoryMemberFragment.newInstance();
            } else if (tabTypeId == 22) {
                myFragment[FRAGMENT_CATEGORY] = ServiceClassFragment.newInstance();
            } else {
                myFragment[FRAGMENT_CATEGORY] = CategoryFragment4.newInstance(false, 1);
            }
            myFragment[FRAGMENT_CHAT] = new ChatFragment();
            //            myFragment[FRAGMENT_BUSINESS] = new BusinessHomeFragment();
            //            myFragment[FRAGMENT_SHOPPING] = new ShoppingCartFragment();
            myFragment[FRAGMENT_SELF] = new SelfFragment5();
            isInit = true;
            upDateApk();
            fragmentManager.beginTransaction().add(R.id.content, myFragment[FRAGMENT_HOME]).commitAllowingStateLoss();
        }
    }


    /**
     * 检查自动更新
     */
    private void upDateApk() {
        if (isInit) {
            if (BuildConfig.BUILD_TYPE.equals("release")) {
                UpdateUtils.getInstance().getNewVersion(this, false);
            }
        }
    }

    public void checkHome() {
        chooseIndex = FRAGMENT_HOME;
        displayFrg(FRAGMENT_HOME);
        binding.bottomNavigationLayout.tabLayout.setVisibility(View.VISIBLE);
        isPick = false;
        showTabView(FRAGMENT_HOME);
    }

    public void checkSelf() {
        chooseIndex = FRAGMENT_SELF;
        displayFrg(FRAGMENT_SELF);
        binding.bottomNavigationLayout.tabLayout.setVisibility(View.VISIBLE);
        isPick = false;
        showTabView(FRAGMENT_SELF);
    }

    public void showTabView(int index) {
        binding.bottomNavigationLayout.tabHome.setViewSelect(false);
//        binding.tabShopping.setViewSelect(false);
        binding.bottomNavigationLayout.tabSelf.setViewSelect(false);
        binding.bottomNavigationLayout.tabChat.setViewSelect(false);
        binding.bottomNavigationLayout.tabBusiness.setViewSelect(false);
        binding.bottomNavigationLayout.tabFenlei.setViewSelect(false);
        initChangeAuth(false);
        switch (index) {
            case FRAGMENT_HOME:
            case FRAGMENT_MAIN_RECRUITMENT:
                binding.bottomNavigationLayout.tabHome.setViewSelect(true);
                changeStatusBar(true);
                break;
            case FRAGMENT_CHAT:
                binding.bottomNavigationLayout.tabChat.setViewSelect(true);
                changeStatusBar(false);
                break;
            case FRAGMENT_BUSINESS:
                binding.bottomNavigationLayout.tabBusiness.setViewSelect(true);
                changeStatusBar(false);
                break;
            case FRAGMENT_SHOPPING:
//                binding.tabShopping.setViewSelect(true);
                changeStatusBar(false);
                break;
            case FRAGMENT_SELF:
                binding.bottomNavigationLayout.tabSelf.setViewSelect(true);
                changeStatusBar(false);
                initChangeAuth(true);
                break;
            case FRAGMENT_CATEGORY:
//                if (!"物流".equals(tabTypeName)) {
//                    CategoryFragment4 categoryFragment4 = (CategoryFragment4) myFragment[index];
//                    categoryFragment4.setGridLayoutManager(tabTypeName);
//                }
                binding.bottomNavigationLayout.tabFenlei.setViewSelect(true);
                changeStatusBar(false);
                break;
        }
    }

    /*
     * 用来判断未实名认证状态下TAB样式修改
     * */
    private void initChangeAuth(boolean flag) {
        if (!SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
            int TYPE = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (TYPE == 0) {
                boolean isAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                if (!isAuth) {
                    if (flag) {
                        upDataMyTabIcom("未实名", R.mipmap.app_tab_self_name_on);
                    } else {
                        upDataMyTabIcom("未实名", R.mipmap.app_tab_self_name_off);
                    }
                }
            }
        }

    }

    private void changeStatusBar(boolean b) {
        if (immersionBar == null) {
            return;
        }
        //加载广告页面时适配底部操作栏
        immersionBar.statusBarDarkFont(b).init();
    }

    public void displayFrg(int index) {
        if (myFragment != null && myFragment[index] != null) {
            if (fragmentManager == null) {
                return;
            }
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (!myFragment[index].isAdded()) {
                if (index == currentIndex) {
                    return;
                }
                transaction.hide(myFragment[currentIndex]).add(R.id.content, myFragment[index]).commitAllowingStateLoss();
            } else {
                transaction.hide(myFragment[currentIndex]).show(myFragment[index]).commitAllowingStateLoss();
            }
            currentIndex = index;
        }
    }

    public void showBottomView(boolean visible) {
        binding.bottomNavigationLayout.tabLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    public void checkPublishData() {
        SharedPreferenceUtil.init(getActivity());
        isEnterpriseAuth = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "");
        isDriverAuth = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DRIVER_AUTH, "");
        isPersonAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
        RELEVANCE = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.RELEVANCE, "");
        IS_GOODS_PUBLISH = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.CHILD_MENU, "").contains(MK_ADDCOMMODITY);
        showLogMsg(mpublishSelectedName);
    }

    public void showPublishPop(List<MenuEntity> data) {
        this.menulist = data;
        if (data == null || data.size() == 0) {
            MToast.showLongToast(this, "暂无发布数据");
            return;
        }
        showBottomDialog();
    }

    public void showShoppingCarView() {
        showTabView(FRAGMENT_SHOPPING);
        displayFrg(FRAGMENT_SHOPPING);
    }

    public void tabSelfClick() {
        binding.bottomNavigationLayout.tabSelf.performClick();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
        switch (v.getId()) {
            case R.id.tab_home:
                isShowLogisticsWork(tabTypeId == 6);
                chooseIndex = FRAGMENT_HOME;
                if (isPick) {
                    showTabView(FRAGMENT_MAIN_RECRUITMENT);
                    displayFrg(FRAGMENT_MAIN_RECRUITMENT);
                } else {
                    showTabView(FRAGMENT_HOME);
                    displayFrg(FRAGMENT_HOME);
                }
                break;
            case R.id.tab_chat:
                isShowLogisticsWork(false);
                chooseIndex = FRAGMENT_CHAT;
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    showTabView(FRAGMENT_CHAT);
                    displayFrg(FRAGMENT_CHAT);
                    isUpdateUnread = false;   //不在此更新未读消息数,由FRAGMENT_CHAT里去监听
                }
                break;

            case R.id.tab_business:
                chooseIndex = FRAGMENT_BUSINESS;
                SharedPreferenceUtil.init(this);
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    long curClickTime = System.currentTimeMillis();
                    if ((curClickTime - lastClickTime) >= 2000) {
                        lastClickTime = curClickTime;
                        showTabView(FRAGMENT_BUSINESS);
                        displayFrg(FRAGMENT_BUSINESS);
                    }
                }
                break;
            case R.id.tab_shopping:
                chooseIndex = FRAGMENT_SHOPPING;
                SharedPreferenceUtil.init(this);
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    viewModel.checkToken(FRAGMENT_SHOPPING);
                }
                break;
            case R.id.tab_self:
                isShowLogisticsWork(false);
                chooseIndex = FRAGMENT_SELF;
                showTabView(FRAGMENT_SELF);
                displayFrg(FRAGMENT_SELF);
                if (myFragment[FRAGMENT_SELF] instanceof SelfFragment5) {
                    ((SelfFragment5) myFragment[FRAGMENT_SELF]).onEvent(new LoginTokenEvent());
                }
                break;
            case R.id.tab_publish:
                if (chooseIndex == FRAGMENT_SELF) {
                    showMinePublishDialog(true, "");
                    return;
                }
                switch (tabTypeId) {
                    case 6://物流货运
                        showBottomLogisticsDialog();
                        break;
                    case 24://会员经营
                        showBottomMemberDialog();
                        break;
                    case 5: //工队工人
                        showPackersDialog();
                        break;
                    case 22: //企业服务
                        SharedPreferenceUtil.init(MainActivity.this);
                        showBottomEnterpriseDialog();
                        break;
                    case 3://集采团购
                        showBottomJiCaiDialog();
                        break;
                    case 2: //招标竞价
                        showPopZhaoCai();
                        break;
                    default:
                        if (selectId == tabTypeId) {
                            showBottomDialog();
                        } else {
                            viewModel.publishMenu(tabTypeId);
                        }
                        selectId = tabTypeId;
                        break;
                }

                break;
            case R.id.tab_fenlei:
                isShowLogisticsWork(tabTypeId == 6);
                chooseIndex = FRAGMENT_CATEGORY;
                showTabView(FRAGMENT_CATEGORY);
                displayFrg(FRAGMENT_CATEGORY);

                break;
        }
    }

    public void showPackersDialog(){
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) != 3){
            showBottomTeamDialog();
        }else {
            MToast.showToast(MainActivity.this, "当前身份不可用，请切换至个人、团队或企业身份");
        }
    }

    /**
     * 底部集采弹窗菜单信息
     */
    private void showBottomJiCaiDialog() {
        HomeJiCaiPublishMenuPop seekingRentSecondPublishDialog = new HomeJiCaiPublishMenuPop(getActivity(), null);
        seekingRentSecondPublishDialog.setData(viewModel.getJiCaiMenuList());
        seekingRentSecondPublishDialog.setDialogClickCallBack(name -> {
            //0个人 1企业 2团队
            int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(MainActivity.this);
            } else {
                switch (name) {
                    case "需方发起"://需方发起
                        JiCaitype = "1";
                        if (type == 1) {
                            if (ButtonClickUtils.isFastClick()) {
                                // 进行点击事件后的逻辑操作
                                startActivity(new Intent(MainActivity.this, JiCaiDemanderPublishAct.class).putExtra("type", JiCaitype));
                            }
                        } else {
                            MToast.showToast(MainActivity.this, "请切换至企业身份进行集采发布");
                        }
                        break;
                    case "企业专项"://企业专项
                        JiCaitype = "2";
                        if (type == 1) {
                            if (ButtonClickUtils.isFastClick()) {
                                // 进行点击事件后的逻辑操作
                                startActivity(new Intent(MainActivity.this, JiCaiDemanderPublishAct.class).putExtra("type", JiCaitype));
                            }
                        } else {
                            MToast.showToast(MainActivity.this, "请切换至企业身份进行集采发布");
                        }
                        break;
                    case "供方发起": //供方发起
                        if (type == 1) {
                            if (ButtonClickUtils.isFastClick()) {
                                // 进行点击事件后的逻辑操作
                                startActivity(new Intent(MainActivity.this, JiCaiSupplierPublishAct.class));
                            }
                        } else {
                            MToast.showToast(MainActivity.this, "请切换至企业身份进行集采发布");
                        }
                        break;

                }
            }
        }).show();
    }

    public void jumpLogin() {
        showDialog3();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isPick) {
                checkHome();
            } else {
                // 判断间隔时间 大于2秒就退出应用
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次关闭应用",
                            Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    //这里写返回后的逻辑（跳到主界面、关闭应用...）
                }
                return false;
            }
        }
        return false;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }

    public void setLogisticsWork() {
        if (tabTypeId == 6) {
            if (logisticsWorkbench == null) {
                newInstanceWorkBench();
            } else {
                logisticsWorkbench.checkUser(this);
            }
            if (chooseIndex == FRAGMENT_HOME || chooseIndex == FRAGMENT_CATEGORY) {
                isShowLogisticsWork(true);
            } else {
                isShowLogisticsWork(false);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    //初始化未读红点动画
    private void initUnreadCover() {
        DropManager.getInstance().init(this, binding.unreadCover, (id, explosive) -> {
                    if (id == null || !explosive) {
                        return;
                    }
                });
    }

    //更新tabbar上未读消息数
    public void updateTabBarUnreadMsg(int unread) {
        if (unread > 0) {
            if (qBadgeView != null) {
                qBadgeView.setBadgeNumber(unread);
            }
        } else {
            //隐藏Badge
            if (qBadgeView != null) {
                qBadgeView.hide(true);
            }
        }
    }

    // 注销
    public static void logout(Context context, boolean quit) {
        Intent extra = new Intent();
        extra.putExtra(EXTRA_APP_QUIT, quit);
        start(context, extra);
    }


    //弹框跳转认证
    public void showDialog() {
        View view = View.inflate(this, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("确定");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("暂无权限，去认证？");

        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            requestAuthWriteStorage();
            roundCornerDialog.dismiss();
        });

        //取消
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    //弹框跳转认证
    public void showDialog2(String id, String msg) {
        View view = View.inflate(this, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("立刻认证");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText(msg);

        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            AuthActivity3.start(getActivity());
            roundCornerDialog.dismiss();
        });

        //取消
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    //未登录弹框跳转认证
    public void showDialog3() {
        View view = View.inflate(this, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("确定");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("未登录，请先登录。");

        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_MAIN_ACTIVITY_JUMP);
            roundCornerDialog.dismiss();
        });

        //取消
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    private void requestAuthWriteStorage() {
        if (PermissionsUtil.hasPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AuthActivity.start(this);
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    AuthActivity.start(getActivity());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    Toast.makeText(MainActivity.this, "请先获相应的操作权限", Toast.LENGTH_LONG).show();
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    //判断点击的功能是否认证通过
    private void showLogMsg(String name) {
        if ("货运发布".equals(name)) {
            MToast.showLongToast(this, "功能开发中,敬请期待");
            return;
        }
        //个人认证
        if (
                "我的函询".equals(name) ||
                        "求租发布".equals(name) ||
                        "货运发布".equals(name) ||
                        "招工用工".equals(name) ||
                        "邀请会员".equals(name) ||
                        "会员审核".equals(name) ||
                        "我的加盟".equals(name) ||
                        "采购订单".equals(name) ||
                        "我的求租".equals(name) ||
                        "申请加盟".equals(name) ||
                        "机械出租".equals(name) ||
                        "设备出租".equals(name) ||
                        "车辆出租".equals(name) ||
                        "房产出租".equals(name) ||
                        "土地出租".equals(name) ||
                        "工厂出租".equals(name) ||
                        "机械发布".equals(name) ||
                        "设备发布".equals(name) ||
                        "车辆发布".equals(name) ||
                        "房产发布".equals(name) ||
                        "土地发布".equals(name) ||
                        "工厂发布".equals(name) ||
                        "农机出租".equals(name) ||
                        "机械求租".equals(name) ||
                        "设备求租".equals(name) ||
                        "车辆求租".equals(name) ||
                        "房产求租".equals(name) ||
                        "土地求租".equals(name) ||
                        "工厂求租".equals(name) ||
                        "农机求租".equals(name) ||
                        "工队简介".equals(name)) {
            if (!isPersonAuth) {
                showDialog2(name, "请先实名认证或企业认证");
                mainPublishDialog.dismiss();
                return;
            }
            //企业认证
            if ("会员审核".equals(name) || "我的加盟".equals(name) || "采购订单".equals(name) || "申请加盟".equals(name) || "邀请会员".equals(name)) {
                if ("SUCCESS".equals(isEnterpriseAuth) || ("1".equals(RELEVANCE) && IS_GOODS_PUBLISH)) {
                    //已认证或者是关联企业有权限
                    isAuth(name);
                    return;
                } else if (!"SUCCESS".equals(isEnterpriseAuth) && ("1".equals(RELEVANCE) && !IS_GOODS_PUBLISH)) {
                    //未认证且是关联企业无权限
                    isAuth(name);
                    return;
                } else {
                    showDialog2(name, "请先实名认证或企业认证");
                    mainPublishDialog.dismiss();
                    return;
                }
            }
            isAuth(name);
        } else {
            if ("询价发布".equals(name)) {
                goLogin(this);
            } else if ("商品发布".equals(name)) {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    ACAdminDialogUtils.showACDialogForPublish(ACAdminDialogUtils.TYPE_NO_LOGIN, getActivity(), null);
                    return;
                } else {
                    if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                        ACAdminDialogUtils.showACDialogForPublish(3, this, new ACAdminDialogUtils.DialogClick() {
                            @Override
                            public void dialogClick1() {
                                CertificationActivity.start(MainActivity.this);
                            }
                        });
                    } else if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                        if ("SUCCESS".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "")) || RELEVANCE.equals("1")) {
                            if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "").equals("个人中心")) {
                                ACAdminDialogUtils.showACDialogForPublish(1, this, new ACAdminDialogUtils.DialogClick() {
                                    @Override
                                    public void dialogClick3() {
                                        displayFrg(3);
                                    }
                                });
                            } else {
                                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.IS_DATA, "").contains("3_shangpinfabu")) {
                                    GoodsPublishActivity.start(getActivity());
                                } else {
                                    MToast.showToast(this, "您没有权限，请联系管理员开通");
                                }
                            }
                        } else {
                            ACAdminDialogUtils.showACDialogForPublish(4, this, new ACAdminDialogUtils.DialogClick() {
                                @Override
                                public void dialogClick2() {
                                    displayFrg(3);
                                }
                            });
                        }
                    }
                }
                return;
            }
        }
    }

    //根据名字跳转到对应的界面
    private void isAuth(String name) {
        switch (name) {
            case "询价发布":
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.IS_DATA, "").contains("common_wodexunjia")) {
                    Intent createGoods = new Intent(getActivity(), NewPurchasesActivity.class);
                    createGoods.putExtra("GOOD_EDIT", false);
                    createGoods.putExtra("GOOD_ADD", false);
                    createGoods.putExtra("GOOD_ENTITY", new GoodsItemEntity());
                    startActivity(createGoods);
                } else {
                    MToast.showToast(this, "您没有权限，请联系管理员开通");
                }
                break;
            case "我的函询":
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(MainActivity.this);
                    return;
                } else {
                    if (!isPersonAuth) {
                        MToast.showToast(this, "请先进行实名认证");
                        return;
                    }
                    WebSiteInquiryActivity.Companion.start(getActivity());
                }
                break;
            case "求租发布":
                showSecondWeightBottomDialog();
                break;
            case "货运发布":
                boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                pushGoodsInfo(personAuth, type, true);
                break;
            case "招工用工":
                PackersEmploymentActivity.start(getActivity());
                break;
            case "邀请会员":
                MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                break;
            case "会员审核":
                MemberAuditActivity.start(this);
                break;
            case "我的加盟":
                MyCenterMyJoinActivity.start(this);
                break;
            case "采购订单":
                ARouter.getInstance().build(Constants.ARouter.AR_PURCHASE_ORDER_LIST).navigation();
                break;
            case "我的求租":
                MyAskLeaseActivity.start(this);
                break;
            case "申请加盟":
                MemberInviteOrApplyActivity.startInviteOrApply(this, 1);
                break;
            case "商品发布":
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.IS_DATA, "").contains("3_shangpinfabu")) {
                    GoodsPublishActivity.start(getActivity());
                } else {
                    MToast.showToast(this, "您没有权限，请联系管理员开通");
                }
                break;
            case "机械发布":
                //机械发布
                LeaseMachineActivity.start(getActivity());//2021年2月2日改成发布页
                break;
            case "设备发布":
                //设备发布
                DevicePublishActivity.start(getActivity());//9月18日改成发布页
                break;
            case "车辆发布":
                //车辆发布
                CarPublishActivity1.start(getActivity());
                break;
            case "房产发布":
                LeaseHousesActivity.start(getActivity());
                break;
            case "土地发布":
                LeaseLandActivity.start(getActivity());
                break;
            case "工厂发布":
                LeaseFactoryActivity.start(getActivity());
                break;
            case "机械出租":
                LeaseMachineActivity.start(getActivity());
                break;
            case "设备出租":
                DevicePublishActivity.start(getActivity());
                break;
            case "车辆出租":
                CarPublishActivity1.start(getActivity());
                break;
            case "房产出租":
                LeaseHousesActivity.start(getActivity());
                break;
            case "土地出租":
                LeaseLandActivity.start(getActivity());
                break;
            case "工厂出租":
                LeaseFactoryActivity.start(getActivity());
                break;
            case "农机出租":
                LeaseFarmActivity.start(getActivity());
                break;
            case "工队简介":
                SelfTeamIntroduceActivity.start(this, null, AppConstant.PAGER_ADD);
                break;
            case "机械求租"://机械
                PublishLeaseInfoActivity2.start(MainActivity.this, 0);
                break;
            case "设备求租": //设备
                PublishLeaseInfoActivity2.start(MainActivity.this, 1);
                break;
            case "车辆求租"://车辆
                PublishLeaseInfoActivity2.start(MainActivity.this, 2);
                break;
            case "房产求租"://房产
                AskLeaseHouseActivity2.start(MainActivity.this);
                break;
            case "土地求租"://土地
                AskLeaseLandActivity2.start(MainActivity.this);
                break;
            case "工厂求租"://工厂
                AskLeaseFactoryActivity2.start(MainActivity.this);
                break;
            case "农机求租"://农机
                AskLeaseFarmActivity2.start(MainActivity.this);
                break;
        }
        mainPublishDialog.dismiss();
    }

    //工队对应发布菜单 权限
    private void teamMenuAuth(String name) {
        boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
        pushTeamInfo(personAuth, name);
    }

    //物流对应发布菜单
    private void logisticsMenuAuth(String name) {
        boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        switch (name) {
            case "发布货运":
                pushGoodsInfo(personAuth, type, true);
                break;
            case "发布竞价":
                pushGoodsInfo(personAuth, type, false);
                break;
            case "发布车辆":
                driverPush(personAuth, type, true);
                break;
            case "发布拉货":
                driverPush(personAuth, type, false);
                break;
        }
    }

    private void driverPush(boolean personAuth, int type, boolean isPushCar) {
        if (personAuth) {
            if (isPushCar) {
                if (type == 0) {//当前个人
                    if (!UserOperating.getInstance().isNotAuthDriver(this)) {
                        AddCarActivity.start(this);
                    }
                } else {
                    AddCarActivity.start(this);
                }

            } else {
                ARouter.getInstance().build(PathLogistics.CarriagePushActivity).navigation();
            }
        } else {//去实名认证
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("您当前未实名认证，是否立即认证？")
                    .cancel("取消")
                    .confirm("确定")
                    .cancelable(false)
                    .confirmCallback(v -> {
                        AuthActivity3.start(MainActivity.this);
                    })
                    .show();
        }
    }

    /**
     * 验证用户信息并发布货源
     *
     * @param personAuth
     * @param type       0个人 1企业 2团队
     * @param isNormal   true:普通货源 false:竞价货源
     */
    private void pushGoodsInfo(boolean personAuth, int type, boolean isNormal) {
        if (personAuth) {
            if (UserOperating.getInstance().getUserInfo() == null) {
                return;
            }
            if (type == 0) {
                if (isNormal) {
                    PublishCargoActivity.start(this);
                } else {
                    PublishCargoActivity.start(this, false);
                }
            } else if (type == 2) {//当前团队
                if (UserOperating.getInstance().isAuthAgentComputer()) {//已认证物流中介
                    if (isNormal) {
                        PublishCargoActivity.start(this);
                    } else {
                        PublishCargoActivity.start(this, false);
                    }
                } else {
                    if (isNormal) {
                        PublishCargoActivity.start(this);
                    } else {
                        PublishCargoActivity.start(this, false);
                    }
                }
            } else {//当前企业
                if (UserOperating.getInstance().hasCompanyPermission(PermissionCheckUtil.KEY_HUOYUANGUANLI)) {//个人加入企业有权限
                    if (isNormal) {
                        PublishCargoActivity.start(this);
                    } else {
                        PublishCargoActivity.start(this, false);
                    }
                } else {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content(UserOperating.getInstance().getTeamOrCompanyName() + "未授予您发布货源的权限。建议您联系管理员分配权限")
                            .singleBtn(true)
                            .confirm("我知道了")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .show();
                }
            }
        } else {//去实名认证
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("您当前未实名认证，是否立即认证？")
                    .cancel("取消")
                    .confirm("确定")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .confirmCallback(v -> {
                        AuthActivity3.start(MainActivity.this);
                    })
                    .show();
        }
    }

    /**
     * 验证用户信息并发布货源
     *
     * @param personAuth
     * @param name       工人发布 发布用工
     */
    private void pushTeamInfo(boolean personAuth, String name) {
        if ("劳务发布".equals(name)) {
            ActivityJump.jumpToActivity(this, LaborServiceAndEmploymentPublishActivity.class);
            return;
        }

        if ("工种报价".equals(name)) {
            SelfTeamOfferEditActivity.start(MainActivity.this, null, 0);
            return;
        }

        if ("工队发布".equals(name)) {
            SelfTeamIntroduceActivity.start(this, null, AppConstant.PAGER_ADD);
            return;
        }

        if (personAuth) {
            switch (name) {
                case "工人发布":
                    SelfWorkerPublishActivity.start(MainActivity.this);
                    break;
                case "用工发布":
                    ActivityJump.jumpToActivityForResult(this, SelfTeamEmploymentEditActivity.class, REQUEST_CODE);
                    break;
            }
        } else {//去实名认证
            new RoundDialog.Builder(this)
                    .title("温馨提示")
                    .content("您还未进行实名认证")
                    .cancel("取消")
                    .confirm("去认证")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .confirmCallback(v -> {
                        CertificationActivity.start(this, "1");
                    })
                    .show();
        }
    }

    /**
     * 初始化物流工作台
     */
    private void newInstanceWorkBench() {
        if (!UserOperating.getInstance().isLogged()) {
            return;
        }
        if (logisticsWorkbench == null) {
            logisticsWorkbench = LogisticsWorkbench.newInstance();
            logisticsWorkbench.attach(MainActivity.this);
        }
    }

    /**
     * 是否展示物流工作台
     *
     * @param isShow
     */
    public void isShowLogisticsWork(boolean isShow) {
        if (logisticsWorkbench == null) {
            return;
        }
        if (!UserOperating.getInstance().isLogged()) {
            logisticsWorkbench.hideWorkbench();
            return;
        }

        if (isShow) {
            logisticsWorkbench.showWorkbench();
        } else {
            logisticsWorkbench.hideWorkbench();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 1) {
            state = data.getIntExtra("state", 0);
        }
        if (data != null && requestCode == RequestCode.CODE_MAP && resultCode == RESULT_OK) {
            AMapAddressEntity entity = data.getParcelableExtra(RouterKey.DATA);
            if (entity != null) {
                LogisticsEvent event = LogisticsEvent.make();
                event.setMessageTag(EventConstant.EVENT_ADDRESS_SELECTED);
                event.setObject(entity);
                EventBus.getDefault().post(event);
            }
        }
    }

    /**
     * 弹出底部对话框
     */
    private void showBottomDialog() {
        if (mainPublishDialog == null) {
            mainPublishDialog = new MainPublishDialog(getActivity(), menulist, null);
            mainPublishDialog.setDialogClickCallBack(new MainPublishDialog.DialogClickCallBack() {
                @Override
                public void onItemClick(String publishSelectedName) {
                    mpublishSelectedName = publishSelectedName;
                    SharedPreferenceUtil.init(MainActivity.this);
                    if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
//                        jumpLogin();
                        VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_MAIN_ACTIVITY_JUMP);
                    } else {
                        checkPublishData();
                    }

                    mainPublishDialog.dismiss();
                }
            });
        }
        if (menulist != null && menulist.size() > 0) {
            mainPublishDialog.setmMenuData(menulist);
            mainPublishDialog.show(getSupportFragmentManager(), "123");
        } else {
            viewModel.publishMenu(tabTypeId);
        }
    }

    /**
     * 弹出底部物流菜单对话框
     */
    private void showBottomLogisticsDialog() {
        SeekingRentSecondPublishDialog seekingRentSecondPublishDialog = new SeekingRentSecondPublishDialog(getActivity(), null);
        seekingRentSecondPublishDialog.setData(viewModel.getLogisticsList());
        seekingRentSecondPublishDialog.setDialogClickCallBack(new SeekingRentSecondPublishDialog.DialogClickCallBack() {
            @Override
            public void onItemClick(String name) {
                mpublishSelectedName = name;
                SharedPreferenceUtil.init(MainActivity.this);
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(MainActivity.this);
                } else {
                    logisticsMenuAuth(mpublishSelectedName);
                }
            }
        }).show();
    }

    /**
     * 弹出底部工队菜单对话框
     */
    @LoginCheck(needRealName = true)
    private void showBottomTeamDialog() {
        SeekingRentSecondPublishDialog seekingRentSecondPublishDialog = new SeekingRentSecondPublishDialog(getActivity(), null);
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        seekingRentSecondPublishDialog.setData(type == 1 ? viewModel.getComList() : viewModel.getPersonTeamList(type));
        seekingRentSecondPublishDialog.setDialogClickCallBack(name -> {
            mpublishSelectedName = name;
            SharedPreferenceUtil.init(MainActivity.this);
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(MainActivity.this);
            } else {
                teamMenuAuth(mpublishSelectedName);
            }
        }).show();
    }

    /**
     * 租赁发布数据弹框
     */
    private void showSecondWeightBottomDialog() {
        SeekingRentSecondPublishDialog seekingRentSecondPublishDialog = new SeekingRentSecondPublishDialog(getActivity(), null);
        seekingRentSecondPublishDialog.setData(viewModel.getLeaseList());
        seekingRentSecondPublishDialog.setDialogClickCallBack(new SeekingRentSecondPublishDialog.DialogClickCallBack() {
            @Override
            public void onItemClick(String name) {
                switch (name) {
                    case "求租机械"://机械
                        PublishLeaseInfoActivity2.start(MainActivity.this, 0);
                        break;
                    case "求租设备": //设备
                        PublishLeaseInfoActivity2.start(MainActivity.this, 1);
                        break;
                    case "求租车辆"://车辆
                        PublishLeaseInfoActivity2.start(MainActivity.this, 2);
                        break;
                    case "求租房产"://房产
                        AskLeaseHouseActivity2.start(MainActivity.this);
                        break;
                    case "求租土地"://土地
                        AskLeaseLandActivity2.start(MainActivity.this);
                        break;
                    case "求租工厂"://工厂
                        AskLeaseFactoryActivity2.start(MainActivity.this);
                        break;
                    case "求租农机"://农机
                        AskLeaseFarmActivity2.start(MainActivity.this);
                        break;
                }
            }
        }).show();
    }

    /**
     * 弹出底部会员菜单对话框
     */
    private void showBottomMemberDialog() {
        boolean personal = UserOperating.getInstance().isPersonal();
        SeekingRentSecondPublishDialog seekingRentSecondPublishDialog = new SeekingRentSecondPublishDialog(getActivity(), null);
        seekingRentSecondPublishDialog.setData(viewModel.getMemberLIst(personal));
        seekingRentSecondPublishDialog.setDialogClickCallBack(new SeekingRentSecondPublishDialog.DialogClickCallBack() {
            @Override
            public void onItemClick(String name) {
                mpublishSelectedName = name;
                SharedPreferenceUtil.init(MainActivity.this);
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(MainActivity.this);
                } else {
                    if (!MemberConfig.getInstance().isPermission()) {
                        MemberConfig.getInstance().showACDialog(getActivity());
                    } else {
                        switch (name) {
                            case "申请加盟":
                                MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 1);
                                break;
                            case "邀请会员":
                                MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                                break;
                            case "会员审核":
                                MemberAuditActivity.start(MainActivity.this);
                                break;
                            case "关注我的":
                                if (UserOperating.getInstance().isPersonal()) {
                                    ACAdminDialogUtils.showACDialogForGoods(ACAdminDialogUtils.TYPE_NO_AC, getActivity());
                                    return;
                                }
                                MemberManageActivity.start(MainActivity.this, 3);
                                break;
                            case "我的关注":
                                if (UserOperating.getInstance().isPersonal()) {
                                    ACAdminDialogUtils.showACDialogForGoods(ACAdminDialogUtils.TYPE_NO_AC, getActivity());
                                    return;
                                }
                                MemberManageActivity.start(MainActivity.this, 2);
                                break;
                        }
                    }
                }
            }
        }).show();
    }

    /**
     * 弹出底部企业服务菜单对话框
     */
    private void showBottomEnterpriseDialog() {
        MainPublishDialog mainPublishDialog;
        if (UserOperating.getInstance().isPersonal()) {
            mainPublishDialog = new MainPublishDialog(getActivity(), viewModel.getEnterpriseList(), null);
        } else {
            mainPublishDialog = new MainPublishDialog(getActivity(), viewModel.getEnterpriseList(), null);
        }
        mainPublishDialog.setDialogClickCallBack(publishSelectedName -> {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(MainActivity.this);
                return;
            }

            if (publishSelectedName.equals("需求报价") ||
                    publishSelectedName.equals("邀请报价") ||
                    publishSelectedName.equals("销售订单") ||
                    publishSelectedName.equals("采购订单")
            ) {
                MToast.showToast(MainActivity.this, "该功能正在建设中");
                return;
            }
            if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                mpublishSelectedName = publishSelectedName;
                enterpriseMenuAuth(mpublishSelectedName);
                mainPublishDialog.dismiss();
            } else {
                com.sgb.kjwl.utils.DialogHelper.showDialog(getActivity(), "温馨提示", "请先完成实名认证", "去认证", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                        mainPublishDialog.dismiss();
                        CertificationActivity.start(getActivity(), "1");
                    }
                });
            }
        });
        mainPublishDialog.show(getSupportFragmentManager(), "123");
    }

    //服务对应发布菜单
    private void enterpriseMenuAuth(String name) {
        switch (name) {
            case "转让发布":
                ActivityJump.jumpToActivity(MainActivity.this, MakeOverPublishMainActivity.class, Pair.create("position", 0));
                break;
            case "服务发布":
                if (UserOperating.getInstance().isPersonal()) {
                    MToast.showToast(this, "请切换企业或者团队后再试");
                } else {
                    ActivityJump.jumpToActivity(MainActivity.this, PublishServiceListActivity.class);
                }
                break;
            case "需求发布":
                AddNeedListActivity.startactivity(MainActivity.this);
                break;
            case "需求报价":
                MToast.showToast(this, "该功能正在建设中");
                break;
            case "团队认证":
                viewModel.gotTeamAuthListActivity();
                break;
            case "邀请报价":
                MToast.showToast(this, "该功能正在建设中");
                break;
            case "邀请加盟":
                if (UserOperating.getInstance().isCompany()) {
                    MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                } else {
                    MToast.showToast(this, "请身份切换为企业或者加入的企业后再试");
                }

                break;
            case "申请加盟":
                if (UserOperating.getInstance().isCompany()) {
                    MemberInviteOrApplyActivity.startInviteOrApply(this, 1);
                } else {
                    MToast.showToast(this, "请身份切换为企业或者加入的企业后再试");
                }

                break;
            case "销售订单":
                MToast.showToast(this, "该功能正在建设中");
                break;
            case "采购订单":
                MToast.showToast(this, "该功能正在建设中");
                break;
        }
    }

    public void gototeamList(Response<BaseEntity<UserAuthMsgEntity>> response) {
        TeamAuthListActivity.start(getActivity(), 0, response.body().getData().getNo(), response.body().getData());
    }

    /**
     * 开启广告
     */
    private void showAdTime() {
        //存储广告本地地址
        String path = MkvUtils.get().getString(MkvUtils.CommomData, CacheMarker.AdvFilePathTag, "");
        if (!TextUtils.isEmpty(path)) {
            if (path.contains("gif")) {
                binding.layoutAdvView.ivAdv.setVisibility(View.GONE);
                binding.layoutAdvView.ivGifAdv.setVisibility(View.VISIBLE);
                try {
                    binding.layoutAdvView.ivGifAdv.setImageDrawable(new GifDrawable(new File(path)));
                } catch (IOException e) {
                    binding.layoutAdvView.tvNum.setVisibility(View.GONE);
                    binding.layoutAdvView.ivAdv.setVisibility(View.GONE);
                    binding.layoutAdvView.ivGifAdv.setVisibility(View.GONE);
                    showMainActivity(null);
                }
            } else {
                binding.layoutAdvView.ivAdv.setVisibility(View.VISIBLE);
                binding.layoutAdvView.ivGifAdv.setVisibility(View.GONE);
                binding.layoutAdvView.ivAdv.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(path)));
            }
            startAdv();
        } else {
            binding.layoutAdvView.tvNum.setVisibility(View.GONE);
            binding.layoutAdvView.ivAdv.setVisibility(View.GONE);
            binding.layoutAdvView.ivGifAdv.setVisibility(View.GONE);
            showMainActivity(null);
        }

        //查询接口同步本地数据
        viewModel.getAdvUrl();
    }

    private void startAdv() {
        //禁止广告页弹出dialog
        com.swgk.core.dialog.DialogHelper.isShow = false;
        handler.sendEmptyMessageDelayed(0, 1000);
        binding.layoutAdvView.tvNum.setVisibility(View.VISIBLE);
        binding.layoutAdvView.ivAdv.setVisibility(View.VISIBLE);
        binding.layoutAdvView.tvNum.setText("跳过  " + number);

        //点击跳过广告
        binding.layoutAdvView.tvNum.setOnClickListener(v -> {
            if (number > 0) {
                //进入主界面
                showMainActivity(null);
                handler.removeCallbacksAndMessages(null);
            }
        });
    }

    private int getCount() {
        number--;
        if (number == 0) {
            //进入主界面
            showMainActivity(null);
            handler.removeCallbacksAndMessages(null);
        }
        return number;
    }

    //进行一个消息的处理
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                int count = getCount();
                binding.layoutAdvView.tvNum.setText("跳过  " + count);
                if (count > 0) {
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            }
        }
    };

    /**
     * 进入主界面
     *
     * @param intent
     */
    private void showMainActivity(Intent intent) {
        //防止广告页面之上弹出dialog
        com.swgk.core.dialog.DialogHelper.isShow = true;
        //基础权限申请弹框
        requestBasicPermission();
        //隐藏广告布局
        binding.layoutAdvView.contextLayout.setVisibility(View.GONE);
        binding.bottomNavigationLayout.contextLayout.setVisibility(View.VISIBLE);

        //广告页面加载完后适配底部操作栏
        View decor = getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        if (tabTypeId == 6) {
            isShowLogisticsWork(true);
        }

        //IM消息未读条数监听注册
        initTalking();
    }

    /**
     * 消息未读条数统计
     */
    private void initTalking() {
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            IMUtils.getInstance().initManager(this, new IMUtils.ListSessionUnRead() {
                @Override
                public void onChanged(int num) {
                    updateTabBarUnreadMsg(num);
                }
            });
            if (myFragment[FRAGMENT_CHAT] instanceof ChatFragment) {
                ((ChatFragment) myFragment[FRAGMENT_CHAT]).refreshChatFragment();
            }
            //IM消息指令拦截处理(用户密码修改)
            IMUtils.getInstance().handleNewsInterception(1, new IMUtils.MsgHandleInterception() {

                @Override
                public void onChangedPassword() {
//                    ChangePasswordActivity.start(getActivity());
                }

                @Override
                public void onRefreshUnRead() {

                }
            });
        } else {
            updateTabBarUnreadMsg(0);
        }
    }

    private void showAuthenDialog(int type) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View layout;

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (type) {
            case 2://司机认证提醒切换
                layout = inflater.inflate(R.layout.dialog_authen_driver_change, null);
                layout.findViewById(R.id.rl_authen_driver).setOnClickListener(view -> {
                    AuthActivity3.start(this);
                    mDialog.dismiss();
                });
                break;
            case 3://货主中介认证
                layout = inflater.inflate(R.layout.dialog_authen_owner_zhongjie_change, null);
                layout.findViewById(R.id.rl_authen_owner).setOnClickListener(view -> {
                    AuthActivity3.start(this);
                    mDialog.dismiss();
                });
                layout.findViewById(R.id.rl_authen_zhongjie).setOnClickListener(view -> {
                    AuthActivity3.start(this);
                    mDialog.dismiss();
                });
                break;
            case 1://司机认证
            default:
                layout = inflater.inflate(R.layout.dialog_authen_driver, null);
                layout.findViewById(R.id.rl_authen_driver).setOnClickListener(view -> {
                    AuthActivity3.start(this);
                    mDialog.dismiss();
                });
        }

        builder.setView(layout);
        builder.setCancelable(true);
        mDialog = builder.show();
        mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeigh = dm.heightPixels;
        CardView cv = mDialog.findViewById(R.id.cv_dialog);
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) cv.getLayoutParams(); //取控件textView当前的布局参数
        linearParams.width = screenWidth - 100;//
        cv.setLayoutParams(linearParams);
        mDialog.findViewById(R.id.iv_cancel).setOnClickListener(v -> mDialog.dismiss());

    }

    public void showMinePublishDialog(boolean isClick, String name) {
        if (isClick) {
            switch (mineTabTypeName) {
                case "oneLevel_wuliuhuoyun"://物流货运
                    showBottomLogisticsDialog();
                    break;
                case "oneLevel_huiyuanjingying"://会员经营
                    showBottomMemberDialog();
                    break;
                case "oneLevel_gongchenggongdui": //工队工人
                    showBottomTeamDialog();
                    break;
                case "oneLevel_qiyefuwu": //企业服务
                    SharedPreferenceUtil.init(MainActivity.this);
                    showBottomEnterpriseDialog();
                    break;
                case "oneLevel_jicaiguanli"://集采团购
                    showBottomJiCaiDialog();
                    break;
                case "oneLevel_zhaocaijingying": //招标竞价
                    showPopZhaoCai();
                    break;
                case "oneLevel_zulinjingying"://租赁
                    viewModel.publishMenuByType("zulin");
                    break;
                default:
                    viewModel.publishMenu();
                    break;
            }
            selectId = -1;
        } else {
            mineTabTypeName = name;
        }
    }

    public void goLogin(Context context) {
        int type = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
        if (type == ACAdminDialogUtils.TYPE_NORMAL) {
            viewModel.getUserInfo();
        } else {
            ACAdminDialogUtils.showACDialogForGoods(type, context);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PermissionUtils.checkPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_START_LOCATION, 0));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event == null) {
            return;
        }
        if (event.getMessageTag() == EventConstant.EVENT_MAIN_INDEX) {
            int obj = 1;
            if (event != null && event.getObject() != null) {
                obj = (int) event.getObject();
            }
            if (obj == 0) {
                chooseIndex = FRAGMENT_HOME;
            }
            showTabView(chooseIndex);
            displayFrg(chooseIndex);
        } else if (event.getMessageTag() == EventConstant.EVENT_LOGIN_OUT) {
            isShowLogisticsWork(false);
            updateTabBarUnreadMsg(0);
            ((HomeFragment3) myFragment[FRAGMENT_HOME]).refresh();
        } else if (event.getMessageTag() == EventConstant.EVENT_LOGIN) {//登录成功
            MLog.d("首頁等都", "" + event.getMessageData());
            ((HomeFragment3) myFragment[FRAGMENT_HOME]).refresh();
            viewModel.getCompanyList();
            //连接IM服务器
            initTalking();
            //获取物流权限
            viewModel.getLogisticsPermissions(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onInstallEvent(InstallEvent event) {
        if (event.getMessageTag() == EVENT_INSTALL_APP) {
            int oldVersion = MkvUtils.get().getInt(MkvUtils.CommomData, CacheMarker.OldVersionCode, 0);
            if (oldVersion <= 202) { // 保证之前老IM的用户升级新IM版本时，能正常升级。
                cleanTokenInfo();
            }
            UpdateUtils.getInstance().install(this, new File((String) event.getMessageData()));
        }
    }

    /**
     * 清除登录信息
     */
    private void cleanTokenInfo() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, "");
        EventBus.getDefault().postSticky(new LoginTokenEvent());
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(String event) {
        if (event.equals("transport_to_login")) {
            jumpLogin();
        } else if (event.equals(EventConstant.EVENT_REFRESH_MAIN)) {//切换用户身份事件
            viewModel.getLogisticsPermissions(false);
            ((HomeFragment3) myFragment[FRAGMENT_HOME]).refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_BIG_HOME_JUMP_CENTER) {
            chooseIndex = FRAGMENT_SELF;
            long curClickTime = System.currentTimeMillis();
            if ((curClickTime - lastClickTime) >= 2000) {
                lastClickTime = curClickTime;
                showTabView(FRAGMENT_SELF);
                displayFrg(FRAGMENT_SELF);
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_CHANGE_TAB) {
            tabTypeId = (int) event.getMessageData();
            isShowLogisticsWork(false);
            switch (tabTypeId) {
                case 6: //物流
                    newInstanceWorkBench();
                    isShowLogisticsWork(binding.layoutAdvView.contextLayout.getVisibility() != View.VISIBLE);
                    myFragment[FRAGMENT_CATEGORY] = MapGoodsAndCarFragment.getInstance(false);
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("图查", R.drawable.tab_map_icon);
                    break;
                case 4: //租赁
                    myFragment[FRAGMENT_CATEGORY] = CategoryLeaseFragment.newInstance();
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("分类", R.drawable.tab_fenlei_icon);
                    break;
                case 24: //会员经营
                    myFragment[FRAGMENT_CATEGORY] = CategoryMemberFragment.newInstance();
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("分类", R.drawable.tab_fenlei_icon);
                    break;
                case 22://企业服务
                    myFragment[FRAGMENT_CATEGORY] = ServiceClassFragment.newInstance();
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("分类", R.drawable.tab_fenlei_icon);
                    break;
                case 5: //工队工人
                    myFragment[FRAGMENT_CATEGORY] = FigureCheckFragment.getInstance(false);
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("图查", R.drawable.tab_map_icon);
                    break;
                case 2: //招采
                    myFragment[FRAGMENT_CATEGORY] = PickCategoryFragment.newInstance();
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("分类", R.drawable.tab_fenlei_icon);
                    break;
                default:
                    myFragment[FRAGMENT_CATEGORY] = CategoryFragment4.newInstance(false, 1);
                    binding.bottomNavigationLayout.tabFenlei.setNameAndIcon("分类", R.drawable.tab_fenlei_icon);
                    break;
            }


        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(WebEvent2 event) {
        if (event.getMessageTag() == EventConstant.EVENT_MATERIAL_FILTER) {
            displayFrg(3);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(CategoryEvent2 event) {
        if (event.getMessageTag() == EventConstant.EVENT_CATEGORY_CHOOSE2) {
            chooseIndex = FRAGMENT_HOME;
            if (isPick) {
                showTabView(FRAGMENT_MAIN_RECRUITMENT);
                displayFrg(FRAGMENT_MAIN_RECRUITMENT);
            } else {
                showTabView(FRAGMENT_HOME);
                displayFrg(FRAGMENT_HOME);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CategoryEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SELECT_TUCHA_TAB) {
            chooseIndex = FRAGMENT_CATEGORY;
            showTabView(FRAGMENT_CATEGORY);
            displayFrg(FRAGMENT_CATEGORY);
            if (myFragment[currentIndex] instanceof MapGoodsAndCarFragment) {
                ((MapGoodsAndCarFragment) myFragment[currentIndex]).setCurrentFragment((int) event.getMessageData());
            }
        }
    }

    /**
     * 招采发布按钮调用弹窗
     */
    public void showPopZhaoCai() {
        PickUtil.showBottomZhaoCaiDialog(this);
    }


    /**
     * @param title        要显示的内容标题
     * @param drawablePath 要显示的图片
     */
    public void upDataMyTabIcom(String title, String drawablePath) {
        binding.bottomNavigationLayout.tabSelf.setNameAndIcon(title, drawablePath);
    }

    /**
     * @param title        要显示的内容标题
     * @param drawablePath 要显示的图片
     */
    public void upDataMyTabIcom(String title, int drawablePath) {
        binding.bottomNavigationLayout.tabSelf.setNameAndIconSelf(title, drawablePath);
    }

    private BackResultContentListener contentListener;

    /**
     * 选首指定接收通知
     * <p>
     * 所有引用选首模块的界面可直接发送通知告诉主界面弹出快捷入口界面
     * EventBus.getDefault().postSticky(new QuickEntryEvent(binding.ivQuickEntry, contentListener));
     * 注：binding.ivQuickEntry为你当前界面选首按钮的ViewID
     * contentListener 为放开给当前界面本身的监听回调，用户处理Activity的关闭以及当前界面的跳转
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(QuickEntryEvent event) {
        contentListener = event.getListener();
        showLeftWindow(event.getView());
    }

    /**
     * 选首弹框界面
     *
     * @param view 选首按钮viewID
     */
    public void showLeftWindow(View view) {
        if (quickEntryPopWindow == null) {
            quickEntryPopWindow = new QuickEntryPopWindow(getActivity());
            //必须调用
            quickEntryPopWindow.setListener(this::onItemClick);
        }
        quickEntryPopWindow.backgroundAlpha(0.5f);
        quickEntryPopWindow.setRecover();
        quickEntryPopWindow.showPopwindowLeft(view);
    }

    /**
     * 快捷菜单的点击事件监听及实现方法
     *
     * @param entity 菜单类
     */
    @Override
    public void onItemClick(QuickEntryEntity entity) {
        //关闭弹框
        if (quickEntryPopWindow != null) {
            quickEntryPopWindow.dismiss();
        }
        if (contentListener != null) {
            if (contentListener.backResult(entity)) {
                return;
            }
        }
        changeTabFragmentEvent(entity.getId());
        switch (entity.getId()) {
            case "0": //首页/网站推荐
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 21));
                break;
            case "1": //商品/销售
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 1));
                break;
            case "1-1": //全部商品
                GoodsAggregateActivity.start(getActivity(), null, 0, "", null, null, false);
                break;
            case "1-2": //自营商品
                GoodsAggregateActivity.start(getActivity(), null, 1, "", null, null, false);
                break;
            case "1-3": //集采商品
                GoodsAggregateActivity.start(getActivity(), null, 2, "", null, null, false);
                break;
            case "1-4": //促销商品
                GoodsAggregateActivity.start(getActivity(), null, 3, "", null, null, false);
                break;
            case "1-5": //供应商
                GoodsAggregateActivity.start(getActivity(), null, 5, "", null, null, false);
                break;
            case "2": //招标竞价
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 2));
                break;
            case "2-1": //招标大厅
                PickListActivity.start(getActivity(), "1", 0);
                break;
            case "2-2": //招标公告
                PickListActivity.start(getActivity(), "2", 0);
                break;
            case "2-3": //直接竞价
                PickBiddingListActivity.start(getActivity());
                break;
            case "2-4": //需求预告
                DemandForecastActivity.start(getActivity());
                break;
            case "2-5": //招标预告
                PickNoticeActivity.start(getActivity());
                break;
            case "2-6": //中标公告
                PickWinningNoticeActivity.start(getActivity());
                break;
            case "3": //集采团购
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 3));
                break;
            case "3-1": //集采大厅
                JiCaiDaTingActivity.start(getActivity());
                break;
            case "3-2": //需方发起
                XuFangFaQiActivity.start(getActivity(), "1");
                break;
            case "3-3": //供方发起
                FactoryCentralizedActivity.start(getActivity());
                break;
            case "3-4": //企业专项
                XuFangFaQiActivity.start(getActivity(), "2");
                break;
            case "3-5": //我的加盟
                if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    MyCenterMyJoinActivity.start(getActivity());
                } else {
                    VerificationCodeLoginActivity.start(getActivity());
                }
                break;
            case "3-6": //我的报价
                if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    JcMyPriceActivity.start(getActivity());
                } else {
                    VerificationCodeLoginActivity.start(getActivity());
                }
                break;
            case "4": //租赁转让
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 4));
                break;
            case "4-1": //出租大厅
                LeaseHallActivity2.start(getActivity());
                break;
            case "4-2": //需求大厅
                LeaseHallActivity2.start(getActivity(), 1, 0);
                break;
            case "5": //工队工人
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 5));
                break;
            case "5-1": //临时用工
                //临时用工-工队首页点击用工需求
                //"用工需求","工人大厅","工队大厅","工种报价","工程分包","工程公司","人气工队"
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity, Pair.create("type", 0));
                break;
            case "5-2": //找工人
                //找工人-工队首页点击个人大厅
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity, Pair.create("type", 1));
                break;
            case "5-3": //施工队
                //施工队，班组工队，劳务公司-工队首页点击工队大厅 {"施工队", "班组工队", "劳务公司", "记工记账"};
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity, Pair.create("type", 2));
                break;
            case "5-4": //班组工队
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity,
                        Pair.create("type", 2), Pair.create("childPosition", 1));
                break;
            case "5-5": //工程公司
                //"用工需求","工人大厅","工队大厅","工种报价","工程分包","工程公司","人气工队"
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity,
                        Pair.create("type", 5));
                break;
            case "5-6": //劳务公司 -工队首页点击工队大厅
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity,
                        Pair.create("type", 2), Pair.create("childPosition", 2));
                break;
            case "5-7": //工种报价
                //"用工需求","工人大厅","工队大厅","工种报价","工程分包","工程公司","人气工队"
                com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.PackersTabActivity, Pair.create("type", 3));
                break;
            case "6": //物流货运
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 6));
                break;
            case "6-1": //货运大厅
                GoodsCarsActivity.start(getActivity(), 0, false);
                break;
            case "6-2": //货车大厅
                GoodsCarsActivity.start(getActivity(), 0, true);
                break;
            case "6-3": //竞价货运
                BiddingTransportHallActivity.start(getActivity());
                break;
            case "6-4": //竞价承运
                DriverLookForGoodsActivity.start(getActivity());
                break;
            case "7": //企业服务
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 22));
                break;
            case "7-1": //服务大厅
                ProfessionalQuoteActivity.start(getActivity());
                break;
            case "7-2": //需求大厅
                NeedActivity.start(getActivity());
                break;
            case "7-3": //知产交易
                ActivityJump.jumpToActivity(getActivity(), MakeOverActivity.class);
                break;
            case "7-4": //专业团队
                ActivityJump.jumpToActivity(getActivity(), ProfessionalTeamChangeActivity.class);
                break;
            case "8": //会员经营
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 24));
                break;
            case "8-1": //会员管理
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getActivity());
                } else {
                    MemberManageActivity.start(getActivity());
                }
                break;
            case "8-2": //邀请会员
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getActivity());
                } else {
                    MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 0);
                }
                break;
            case "8-3": //申请加盟
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getActivity());
                } else {
                    MemberInviteOrApplyActivity.startInviteOrApply(getActivity(), 1);
                }
                break;
            case "8-4": //会员审核
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getActivity());
                } else {
                    MemberAuditActivity.start(getActivity());
                }
                break;
            case "9": //企业经营
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 23));
                break;
            case "9-1": //经营大厅
                String longitude = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
                String latitude = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
                ActivityJump.jumpToActivity(getActivity(), ManageActivity.class, Pair.create("latitude", latitude), Pair.create("longitude", longitude));
                break;
            case "9-2": //专项资质
                SpecialQualificationActivity.startAction(getActivity());
                break;
            case "9-3": //知识产权
                IPActivity.startAction(getActivity());
                break;
            case "9-4": //专项资产
                EpAssestActivity.start(getActivity());
                break;
            case "9-5": //荣誉荣耀
                TradeHonorActivity.start(getActivity());
                break;
            case "9-6": //经营动态
                ActivityJump.jumpToActivity(getActivity(), CompanyTradesActivity.class);
                break;
            case "10": //招商引资
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 27));
                break;
            case "10-1": //投资项目
                ARouter.getInstance().build(PathMerchant.InvestmentProjectActivity).navigation();
                break;
            case "10-2": //投资需求
                ARouter.getInstance().build(PathMerchant.DemandListActivity).navigation();
                break;
        }

    }

    private void changeTabFragmentEvent(String id) {
        if (!TextUtils.isEmpty(id) && id.contains("-")) {
            int newId = Integer.parseInt(id.substring(0, id.indexOf("-")));
            switch (newId) {
                case 1:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 1));
                    break;
                case 2:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 2));
                    break;
                case 3:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 3));
                    break;
                case 4:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 4));
                    break;
                case 5:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 5));
                    break;
                case 6:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 6));
                    break;
                case 7:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 22));
                    break;
                case 8:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 24));
                    break;
                case 9:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 23));
                    break;
                case 10:
                    EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 27));
                    break;
            }
        }
    }
}

